﻿using System;
using System.Threading.Tasks;
using System.Windows.Forms;
using Autofac;
using log4net;
using PortableVersion.Core.FileSystem.Services;

namespace PortableVersion
{
    public partial class CheckoutForm : Form
    {
        private readonly ILog _log;

        public CheckoutForm(ILog log)
        {
            _log = log;
            InitializeComponent();
        }

        private void fromButton_Click(object sender, EventArgs e)
        {
            if (openFolder.ShowDialog() == DialogResult.OK)
            {
                fromTxt.Text = openFolder.SelectedPath;
            }
        }

        private void toButton_Click(object sender, EventArgs e)
        {
            if (openFolder.ShowDialog() == DialogResult.OK)
            {
                toTxt.Text = openFolder.SelectedPath;
            }
        }

        private readonly IContainer _container = BootStapper.Container.Instance;

        private void okButton_Click(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(fromTxt.Text) || String.IsNullOrEmpty(toTxt.Text))
            {
                MessageBox.Show(@"Please provide valid input.");
                return;
            }

            progressBar.Visible = true;
            timer1.Start();
            Task.Factory.StartNew(
                () =>
                    {
                        var svc = _container.Resolve<CheckOutService>(
                            new[]
                                {
                                    new NamedParameter("sourcePath", fromTxt.Text),
                                    new NamedParameter("targetPath", toTxt.Text)
                                });
                        svc.Run();
                    }
                )
                .ContinueWith(
                    t =>
                        {
                            progressBar.Visible = false;
                            timer1.Stop();
                            if (t.IsFaulted && t.Exception != null)
                            {
                                _log.Error("Check out did not succeed.", t.Exception.InnerException);
                                MessageBox.Show(t.Exception.InnerException.Message);
                            }
                            else
                            MessageBox.Show(@"Check out finished");
                        }
                        , TaskScheduler.FromCurrentSynchronizationContext()
                );
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (progressBar.Value > 95)
            {
                progressBar.Value = 0;
            } 
            progressBar.Value += 5;
        }

        internal void SetCheckOut(string folder)
        {
            fromTxt.Text = folder;
        }
    }
}
